package com.example.paymentdemo.contorller;

import com.example.paymentdemo.service.WxPayService;
import com.example.paymentdemo.util.HttpUtils;
import com.example.paymentdemo.util.WechatPay2ValidatorForRequest;
import com.example.paymentdemo.vo.R;
import com.google.gson.Gson;
import com.wechat.pay.contrib.apache.httpclient.auth.Verifier;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;

/**
 * @Author 上号
 * @Date 2022/5/17 22:11
 * @Version 1.0
 */
@RestController
@RequestMapping("/api/wx-pay")
//跨域
@CrossOrigin
@Slf4j
public class WxPayController {
    @Resource
    private WxPayService wxPayService;
    @Resource
    private Verifier verifier;

    /**
     * Native下单
     *
     * @param productId
     * @return
     * @throws Exception
     */

    @PostMapping("/native/{productId}")
    public R nativePay(@PathVariable Long productId) throws Exception {
        log.info("发起支付请求");
        //返回支付二维码连接和订单号
        Map<String, Object> map = wxPayService.nativePay(productId);
        return R.ok().setData(map);
    }

    /**
     * 支付通知 微信支付通过支付通知接口将用户支付成功消息通知给商户
     *
     * @param request  请求
     * @param response 应答
     * @return
     */
    @PostMapping("/native/notify")
    public String nativeNotify(HttpServletRequest request, HttpServletResponse response) {
        //应答对象
        Map<String, String> map = new HashMap<>();
        Gson gson = new Gson();
        try {
            // 请求体转String
            String bodyStr = HttpUtils.readData(request);

            Map<String, Object> mapBody = gson.fromJson(bodyStr, HashMap.class);
            String requestId = (String) mapBody.get("id");
            log.info("id是====> {}", mapBody.get("id"));
            log.info("body====> {}", bodyStr);
            // 验签处理
            WechatPay2ValidatorForRequest wechatPay2ValidatorForRequest = new WechatPay2ValidatorForRequest(verifier, bodyStr, requestId);
            if (!wechatPay2ValidatorForRequest.validate(request)) {
                // 测试错误应答
                response.setStatus(500);
                map.put("code", "ERROR");
                map.put("message", "通知验签失败");
                return gson.toJson(map);
            }
            //处理订单
            wxPayService.processOrder(mapBody);

            log.info("验签成功！！！！！");
            response.setStatus(200);
            map.put("code", "SUCCESS");
            map.put("message", "成功");
            return gson.toJson(map);
        } catch (Exception e) {
            e.printStackTrace();
            // 测试错误应答
            response.setStatus(500);
            map.put("code", "ERROR");
            map.put("message", "系统错误");
            return gson.toJson(map);

        }

    }
}
